package com.clannad.eduservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.clannad.commonutils.JwtUtils;
import com.clannad.commonutils.R;
import com.clannad.commonutils.UcenterMember;
import com.clannad.eduservice.entity.EduComment;
import com.clannad.eduservice.feign.UcenterClient;
import com.clannad.eduservice.service.EduCommentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author clannad
 * @since 2022-08-22
 */
@RestController
@RequestMapping("/eduservice/comment")
//@CrossOrigin
public class EduCommentController {
    @Autowired
    EduCommentService eduCommentService;
    @Autowired
    UcenterClient ucenterClient;

    @GetMapping("/{page}/{limit}")
    public R index(@PathVariable Long page,@PathVariable Long limit,String courseId){
        Page<EduComment> pageParam = new Page<>(page, limit);
        LambdaQueryWrapper<EduComment> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        if(!StringUtils.isEmpty(courseId)){
            lambdaQueryWrapper.eq(EduComment::getCourseId,courseId);
        }
        lambdaQueryWrapper.orderByDesc(EduComment::getGmtCreate);
        eduCommentService.page(pageParam,lambdaQueryWrapper);
        List<EduComment> commentList = pageParam.getRecords();
        Map<String, Object> map = new HashMap<>();
        map.put("items", commentList);
        map.put("current", pageParam.getCurrent());
        map.put("pages", pageParam.getPages());
        map.put("size", pageParam.getSize());
        map.put("total", pageParam.getTotal());
        map.put("hasNext", pageParam.hasNext());
        map.put("hasPrevious", pageParam.hasPrevious());
        return R.ok().data(map);
    }

    @PostMapping("auth/save")
    public R save(@RequestBody EduComment comment, HttpServletRequest request) {
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if(StringUtils.isEmpty(memberId)) {
            return R.error().code(28004).message("请登录");
        }
        comment.setMemberId(memberId);
        UcenterMember ucenterInfo = ucenterClient.getInfo(memberId);
        if(ucenterInfo!=null){
            comment.setNickname(ucenterInfo.getNickname());
            comment.setAvatar(ucenterInfo.getAvatar());
        }
        System.out.println(ucenterInfo);
        eduCommentService.save(comment);
        return R.ok();
    }
}

